package com.pinusmusic.service.impl;

import com.pinusmusic.dao.MusicDao;
import com.pinusmusic.dao.SingerDao;
import com.pinusmusic.dao.impl.MusicDaoImpl;
import com.pinusmusic.dao.impl.SingerDaoImpl;
import com.pinusmusic.domain.*;
import com.pinusmusic.service.MusicService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

public class MusicServiceImpl implements MusicService {
    private MusicDao musicDao = new MusicDaoImpl();
    private SingerDao singerDao = new SingerDaoImpl();
    @Override
    public PageBean<Music> findMusicsByName(int currentPage, int rows, String name) {
        PageBean<Music> pageBean = new PageBean<>();
        //2.获取总记录数
        int totalCount = musicDao.getTotalCount(name);
        pageBean.setTotalCount(totalCount);
        //3.设置总页码数
        int totalPage = totalCount%rows==0?(totalCount/rows):(totalCount/rows)+1;
        pageBean.setTotalPage(totalPage);
        //4.设置当前页码数,设置边界值
        if (currentPage<=0) currentPage=1;
        if (currentPage>=totalPage && totalPage>0) currentPage=totalPage;
        pageBean.setCurrentPage(currentPage);
        //5.设置每页查询的条数
        pageBean.setPageSize(rows);
        //6.设置对应数据
        int start =(currentPage-1)*rows;
        List<Music> musicList = musicDao.findMusicsByName(start, rows, name);
        if (musicList!=null){
            for (int i = 0; i < musicList.size(); i++) {
                Singer singerBySid = singerDao.findSingerBySid(musicList.get(i).getSid());
                musicList.get(i).setSinger(singerBySid);
            }}
        pageBean.setList(musicList);
        return pageBean;
    }
    @Override
    public List<Music> findMusicBySid(Integer sid) {
        return musicDao.findMusicBySid(sid);
    }

    @Override
    public int getTotalCount(int mlid) {
        return musicDao.getTotalCount(mlid);
    }

    @Override
    public PageBean<Music> findMusicByPage(int currentPage, int rows, int mlid) {
        PageBean<Music> pageBean = new PageBean<>();
        //设置总数
        int totalCount = musicDao.getTotalCount(mlid);
        pageBean.setTotalCount(totalCount);
        //设置总页数
        int totalPage = totalCount % rows == 0 ? (totalCount / rows) : (totalCount / rows) + 1;
        pageBean.setTotalPage(totalPage);
        //设置当前页码数 ,设置边界值
        if (currentPage <= 0) currentPage = 1;
        if (currentPage >= totalPage && totalPage > 0) currentPage = totalPage;
        pageBean.setCurrentPage(currentPage);

        //5.设置每页查询的条数
        pageBean.setPageSize(rows);
        int start = (currentPage - 1) * rows;
        List<Music> musicByPage = musicDao.findAllMusicByPage(start, rows, mlid);
        pageBean.setList(musicByPage);
        return pageBean;
    }

    @Override
    public PageBean<Music> findMusicInListByPage(int currentPage, int rows, int mlid) {
        PageBean<Music> pageBean = new PageBean<>();
        //设置总数
        int totalCount = musicDao.getCount(mlid);
        pageBean.setTotalCount(totalCount);
        //设置总页数
        int totalPage = totalCount % rows == 0 ? (totalCount / rows) : (totalCount / rows) + 1;
        pageBean.setTotalPage(totalPage);
        //设置当前页码数 ,设置边界值
        if (currentPage <= 0) currentPage = 1;
        if (currentPage >= totalPage && totalPage > 0) currentPage = totalPage;
        pageBean.setCurrentPage(currentPage);
        //5.设置每页查询的条数
        pageBean.setPageSize(rows);
        int start = (currentPage - 1) * rows;
        List<Music> musicByPage = musicDao.findMusicInListByPage(start, rows, mlid);
        pageBean.setList(musicByPage);
        return pageBean;
    }

    @Override
    public int getCount(int mlid) {
        return musicDao.getCount(mlid);
    }

    // 1.创建磁盘文件项工厂
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // 2.创建文件上传的核心类
    ServletFileUpload upload = new ServletFileUpload(factory);

    @Override
    public ResultInfo musicUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        boolean flag = false;//是否成功上传
        String errorMsg = "";
        String filepath = "";
        int sid = 0;
        Music music = new Music();
        // 3.解析request-获得文件项集合
        List<FileItem> list = null;
        try {
            list = upload.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }


        // 4.遍历文件项集合,并记录需要写入数据库的信息
        for (FileItem item : list) {
            boolean formField = item.isFormField();// 是否是一个普通表单项
            if (formField) {
                // 普通表单项
                String fieldName = item.getFieldName();
                String fieldValue = item.getString("utf-8");
                System.out.println("上传的是普通表单项" + fieldName + "---" + fieldValue);
            } else {
                // 文件上传项
                //共4项   (短)musicname filename musicpath filepath(长)
                String musicname = item.getName();
                //覆潮之下.mp3
                String musicpath = null;
                //获得的文件名至少为%.%,若长度小于3则无效不写入
                if (musicname.length() >= 3) {
                    InputStream in = item.getInputStream();
                    String path = req.getServletContext().getRealPath("musics");
                    String filename = UUID.randomUUID() + musicname;
                    //f43910b7-b9f8-4f48-affe-79ccefbeecee覆潮之下.mp3
                    System.out.println("服务器上音乐文件名是" + filename);
                    musicname = musicname.substring(0, musicname.lastIndexOf("."));
                    //覆潮之下
                    System.out.println("要存进数据库的音乐名是" + musicname);
                    filepath = path + "\\" + filename;
                    //F:\Java\pinusmusic\src\main\webapp\music\f43910b7-b9f8-4f48-affe-79ccefbeecee覆潮之下.mp3
                    musicpath = filepath.substring(filepath.lastIndexOf("webapp\\") + 7);
                    //music\f43910b7-b9f8-4f48-affe-79ccefbeecee覆潮之下.mp3
                    System.out.println("要存进数据库的音乐文件路径是" + musicpath);
                    System.out.println("上传音乐文件路径是" + filepath);

                    //复制到资源文件夹
                    OutputStream out = new FileOutputStream(filepath);
                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while ((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    in.close();
                    out.close();
                } else {
                    errorMsg = "上传的文件名不正确";
                    break;
                }
                Singer singer = (Singer) req.getSession().getAttribute("singer");
                sid = singer.getSid();
                System.out.println("sid为" + sid);
                music.setSid(sid);
                music.setMusicname(musicname);
                music.setMusicpath(musicpath);

                //将音乐文件名和可使用的音乐文件路径写入数据库
                if (musicpath != null && musicDao.musicUpload(music)) {
                    flag = true;
                } else {
                    errorMsg = "写入数据库时发生错误";
                    break;
                }
            }
        }

        //返回json信息
        ResultInfo info = new ResultInfo();
        info.setFlag(flag);
        if (!flag) {
            info.setErrorMsg(errorMsg);
        } else {
            info.setData(filepath);
            info.setErrorMsg("写入成功");
        }

        return info;
    }

    @Override
    public ResultInfo musicDelete(HttpServletRequest req, HttpServletResponse resp) {
        boolean flag = false;
        String errorMsg = "";
        String mid = req.getParameter("mid");
        //Music music = (Music) req.getSession().getAttribute("music");
        //int mid = music.getMid();
        System.out.println("mid=" + mid);
        String delmusicpath = musicDao.findPathByMid(Integer.parseInt(mid));
        if (delmusicpath != null) {
            File file = new File(delmusicpath);
            file.delete();
        } else {
            errorMsg = "无法查找到目标文件路径";
            System.out.println(errorMsg);
        }

        ResultInfo info = new ResultInfo();
        flag = musicDao.musicDelete(Integer.parseInt(mid));
        info.setFlag(flag);
        if (!flag) {
            info.setErrorMsg(errorMsg);
        } else {
            info.setData(delmusicpath);
            info.setErrorMsg("删除成功");
        }
        return info;
    }

    @Override
    public ResultInfo musicUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        boolean flag = false;//是否成功更新到webapp内
        String errorMsg = "";
        String filepath = "";
        Music music = new Music();
        Music music1 = (Music) req.getSession().getAttribute("music");
        System.out.println("mid为" + music1.getMid());
        music.setMid(music1.getMid());
        // 3.解析request-获得文件项集合
        List<FileItem> list = null;
        try {
            list = upload.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }


        // 4.遍历文件项集合,并记录需要写入数据库的信息
        for (FileItem item : list) {
            boolean formField = item.isFormField();// 是否是一个普通表单项
            if (formField) {
                // 普通表单项
                String fieldName = item.getFieldName();
                String fieldValue = item.getString("utf-8");
                if (fieldName.equals("mid")) {

                } else if (fieldName.equals("mlid")) {

                } else if (fieldName.equals("sid")) {
                    music.setSid(Integer.parseInt(fieldValue));
                } else {
                    errorMsg = "输入了意料之外的键名" + fieldName;
                    break;
                }

                System.out.println("上传的是普通表单项" + fieldName + "---" + fieldValue);
            } else {

                if (music.getSid() <= 0) {
                    errorMsg = "sid输入错误";
                    break;
                }

                // 文件上传项
                // 获得上传文件的名称
                String musicname = item.getName();
                //覆潮之下.mp3
                String musicpath = null;
                //获得的文件名至少为%.%,若长度小于3则无效不写入
                if (musicname.length() >= 3) {
                    InputStream in = item.getInputStream();
                    String path = req.getServletContext().getRealPath("musics");
                    String filename = UUID.randomUUID() + musicname;
                    //f43910b7-b9f8-4f48-affe-79ccefbeecee覆潮之下.mp3
//                    System.out.println("服务器上音乐文件名是"+filename);
                    musicname = musicname.substring(0, musicname.lastIndexOf("."));
                    //覆潮之下
                    System.out.println("要存进数据库的音乐名是" + musicname);

                    filepath = path + "\\" + filename;
                    //F:\Java\pinusmusic\src\main\webapp\music\f43910b7-b9f8-4f48-affe-79ccefbeecee覆潮之下.mp3
                    musicpath = filepath.substring(filepath.lastIndexOf("webapp\\") + 7);
                    //music\f43910b7-b9f8-4f48-affe-79ccefbeecee覆潮之下.mp3
                    System.out.println("要存进数据库的音乐文件路径是" + musicpath);
//                    System.out.println("上传音乐文件路径是" + filepath);

                    music.setMusicname(musicname);
                    music.setMusicpath(musicpath);

                    //复制到资源文件夹
                    OutputStream out = new FileOutputStream(filepath);
                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while ((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    in.close();
                    out.close();
                } else {
                    errorMsg = "上传的文件名不正确";
                    break;
                }

                String delmusicpath = musicDao.findPathByMid(music.getMid());
                if (delmusicpath != null) {
                    File file = new File(delmusicpath);
                    file.delete();
                } else {
                    errorMsg = "原音乐文件路径丢失或无法删除";
                    break;
                }

                //将音乐文件名和可使用的音乐文件路径写入数据库
                if (musicpath != null && musicDao.musicUpdate(music)) {
                    flag = true;
                } else {
                    errorMsg = "更新数据库记录时发生错误";
                    break;
                }
            }
        }

        //返回json信息
        ResultInfo info = new ResultInfo();
        info.setFlag(flag);
        if (!flag) {
            info.setErrorMsg(errorMsg);
        } else {
            info.setData(filepath);
            info.setErrorMsg("写入成功");
        }
        return info;
    }

    @Override
    public PageBean<Music> findSingerMusicByPage(int currentPage, int rows, Integer sid) {
        PageBean<Music> pageBean = new PageBean<>();
        //设置总数
        int totalCount = musicDao.getTotalCountBySid(sid);
        pageBean.setTotalCount(totalCount);
        //设置总页数
        int totalPage = totalCount % rows == 0 ? (totalCount / rows) : (totalCount / rows) + 1;
        pageBean.setTotalPage(totalPage);
        //设置当前页码数 ,设置边界值
        if (currentPage <= 0) currentPage = 1;
        if (currentPage >= totalPage && totalPage > 0) currentPage = totalPage;
        pageBean.setCurrentPage(currentPage);
        //5.设置每页查询的条数
        pageBean.setPageSize(rows);
        int start = (currentPage - 1) * rows;
        List<Music> musicByPage = musicDao.findSingerMusicByPage(start, rows, sid);
        pageBean.setList(musicByPage);
        return pageBean;
    }

    @Override
    public Music findMusicByMid(int mid) {
        return musicDao.findMusicByMid(mid);
    }

    @Override
    public Map<Music, List<String>> randMusic() {
        List<Music> musics = musicDao.find20Music();
        Map<Music, List<String>> map = new HashMap<>();
        for (int i = 0; map.size()<5; i++) {
            List<Music>musicss=new ArrayList<>(musics);
            System.out.println(musicss.size());
            Music music = musicss.get((int) (Math.random() * musics.size()));
            musicss.remove(music);
            List<String> list = new ArrayList<>();
            List<Music> newmusics=new ArrayList<>(musicss);
            for (int j = 0; j < 3; j++) {
                int i1 = (int) (Math.random() * newmusics.size());
                list.add(newmusics.get(i1).getMusicname());
                newmusics.remove(i1);
            }
            list.add(music.getMusicname());
            System.out.println(list);
            Collections.shuffle(list);
            map.put(music,list);
            list=null;
        }
        return map;
    }

    @Override
    public PageBean<Music> findMusicsByLyrics(int currentPage, int rows, String lyrics) {
        PageBean<Music> pageBean = new PageBean<>();
        //2.获取总记录数
        int totalCount = musicDao.getCountByLyrics(lyrics);
        pageBean.setTotalCount(totalCount);
        //3.设置总页码数
        int totalPage = totalCount%rows==0?(totalCount/rows):(totalCount/rows)+1;
        pageBean.setTotalPage(totalPage);
        //4.设置当前页码数,设置边界值
        if (currentPage<=0) currentPage=1;
        if (currentPage>=totalPage && totalPage>0) currentPage=totalPage;
        pageBean.setCurrentPage(currentPage);
        //5.设置每页查询的条数
        pageBean.setPageSize(rows);
        //6.设置对应数据
        int start =(currentPage-1)*rows;
        List<Music> musicList = musicDao.findMusicsByLyrics(start, rows, lyrics);
        pageBean.setList(musicList);
        return pageBean;
    }

    @Override
    public PageBean<Music> findMusicsBySort(int currentPage, int rows, int languageid, int styleid) {
        PageBean<Music> pageBean = new PageBean<>();
        //2.获取总记录数
        int totalCount = musicDao.getCountBySort(languageid,styleid);
        pageBean.setTotalCount(totalCount);
        //3.设置总页码数
        int totalPage = totalCount%rows==0?(totalCount/rows):(totalCount/rows)+1;
        pageBean.setTotalPage(totalPage);
        //4.设置当前页码数,设置边界值
        if (currentPage<=0) currentPage=1;
        if (currentPage>=totalPage && totalPage>0) currentPage=totalPage;
        pageBean.setCurrentPage(currentPage);
        //5.设置每页查询的条数
        pageBean.setPageSize(rows);
        //6.设置对应数据
        int start =(currentPage-1)*rows;
        List<Music> musicList = musicDao.findMusicsBySort(start, rows, languageid,styleid);
        pageBean.setList(musicList);
        return pageBean;
    }

    @Override
    public MusicStyle findMusicStyle(Integer musicstyleid) {
        return musicDao.findMusicStyle(musicstyleid);
    }

    @Override
    public MusicLanguage findMusicLang(Integer musiclanguageid) {
        return musicDao.findMusicLang(musiclanguageid);
    }

    @Override
    public List<Comment> findCommentsByMid(Integer mid) {
        return musicDao.findCommentsByMid(mid);
    }

    @Override
    public User findUserByUid(Integer uid) {
        return musicDao.findUserByUid(uid);
    }

    @Override
    public int findCommentsCounts(Integer mid) {
        return musicDao.findCommentsCounts(mid);
    }

    @Override
    public void addComment(Comment comment) {
        musicDao.addComment(comment);
    }

    @Override
    public Singer findSingerByMid(Integer sid) {
        return musicDao.findSingerByMid(sid);
    }

    @Override
    public List<Music> findAllMusic() {
        return musicDao.findAllMusic();
    }

    @Override
    public Singer findSingerBySid(Integer sid) {
        return musicDao.findSingerBySid(sid);
    }

    @Override
    public int findFavorsCounts(Integer mid) {
        return musicDao.findFavorsCounts(mid);
    }

    @Override
    public List<Music> findMusicByMlid(Integer mlid) {
        return musicDao.findMusicsByMlid(mlid);
    }
}
